package com.siha_back.common;


import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/*图片/PDF转文字*/

public class FileTextExtractor {

    /**
     * 提取文件文字（支持PDF、图片）
     * @param fileBytes 文件字节数组
     * @param fileName 文件名（含扩展名）
     * @return 提取的文字内容
     */
    public String extractText(byte[] fileBytes, String fileName) {
        String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        try (InputStream inputStream = new ByteArrayInputStream(fileBytes)) {
            switch (extension) {
                case "pdf":
                    return extractPdfText(inputStream);
                case "png": case "jpg": case "jpeg":
                    return extractImageText(fileBytes);
                default:
                    throw new IllegalArgumentException("不支持的文件类型: " + extension);
            }
        } catch (IOException e) {
            throw new RuntimeException("文件读取失败: " + e.getMessage());
        }
    }

    // 提取PDF文字(PDFBox)  Tika可以处理PDF/Word/PPT......
    private String extractPdfText(InputStream inputStream) {
        try (PDDocument document = PDDocument.load(inputStream)) {
            PDFTextStripper stripper = new PDFTextStripper();
            String text = stripper.getText(document);
           // System.out.println(text);
            return text;
        } catch (IOException e) {
            throw new RuntimeException("PDF解析失败: " + e.getMessage());
        }
    }

    // 提取图片文字（OCR）Tess4J
    private String extractImageText(byte[] imageBytes) {
        Tesseract tesseract = new Tesseract();
        // 配置Tesseract数据路径（需提前下载OCR训练数据，如eng.traineddata）
        tesseract.setDatapath("path/to/tessdata");
        tesseract.setLanguage("eng"); // 识别语言，可改为"chi_sim"识别中文
        try {
            // 将byte[]转为BufferedImage
            BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
            return tesseract.doOCR(image);
        } catch (TesseractException e) {
            throw new RuntimeException("图片文字识别失败: " + e.getMessage());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}